<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="充气编号" prop="fullfillNum">-->
<!--        <el-input-->
<!--          v-model="queryParams.fullfillNum"-->
<!--          placeholder="请输入充气编号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="车头号码" prop="carHeadNum">
        <el-input
          v-model="queryParams.carHeadNum"
          placeholder="请输入车头号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充气量" prop="fullfillAmount">
        <el-input
          v-model="queryParams.fullfillAmount"
          placeholder="请输入充气量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售价格" prop="salePrice">
        <el-input
          v-model="queryParams.salePrice"
          placeholder="请输入销售价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="核销状态" prop="checkStatus">
        <el-select
          v-model="queryParams.checkStatus"
          placeholder="核销状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.gas_check_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="充装排序" prop="fullfillSort">-->
<!--        <el-input-->
<!--          v-model="queryParams.fullfillSort"-->
<!--          placeholder="请输入充装排序"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="记录人员" prop="recordPerson">
        <el-input
          v-model="queryParams.recordPerson"
          placeholder="请输入充装记录人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录时间" prop="recordTime">
        <el-date-picker clearable
          v-model="queryParams.recordTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择记录开始时间">
        </el-date-picker>
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择记录结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="充装气站" prop="stationId">
        <el-select
          v-model="queryParams.stationId"
          placeholder="充装气站"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="station in stationList"
            :key="station.stationName"
            :value="station.stationId"
            :label="station.stationName"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gas:fullfill:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['gas:fullfill:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gas:fullfill:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gas:fullfill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fullfillList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="充装记录ID" align="center" prop="fullfillId" v-if="false" />
<!--      <el-table-column label="机器类型" align="center" prop="machineType" />-->
      <el-table-column label="充气编号" align="center" prop="fullfillNum" />
<!--      <el-table-column label="车次排列" align="center" prop="carNumSort" />-->
      <el-table-column label="车辆ID" align="center" prop="carId" v-if="false" />
      <el-table-column label="车头号码" align="center" prop="carHeadNum" />
      <el-table-column label="车身号码" align="center" prop="carBodyNum" />
      <el-table-column label="所属单位" align="center" prop="customerName" />
      <el-table-column label="充气量（m³）" align="center" prop="fullfillAmount" />
      <el-table-column label="进气价格（元）" align="center" prop="salePrice" />
      <el-table-column label="合计金额（元）" align="center" prop="totalAmount" />
      <el-table-column label="核销状态" align="center" prop="checkStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.checkStatus == 0">未核销</span>
          <span v-else-if="scope.row.checkStatus == 1">已核销</span>
          <span v-else-if="scope.row.checkStatus == 2">已作废</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="充装排序" align="center" prop="fullfillSort" />-->
      <el-table-column label="充装人员" align="center" prop="recordPerson" />
      <el-table-column label="充装日期" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="充装站ID" align="center" prop="stationId" />
      <el-table-column label="充装站名" align="center" prop="stationName" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span v-if="scope.row.checkStatus == 0">
            <el-button size="mini" type="text" icon="el-icon-success" @click="handleCheckPass(scope.row)" v-hasPermi="['gas:fullfill:edit']">
              核销
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-remove" @click="handleCheckFail(scope.row)" v-hasPermi="['gas:fullfill:edit']">
              作废
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['gas:fullfill:remove']">
              删除
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-printer" @click="handlePrint(scope.row)" v-hasPermi="['gas:fullfill:export']">
              打印
            </el-button>
          </span>
          <span v-else-if="scope.row.checkStatus == 1">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['gas:fullfill:remove']">
              删除
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-printer" @click="handlePrint(scope.row)" v-hasPermi="['gas:fullfill:export']">
              打印
            </el-button>
          </span>
          <span v-else-if="scope.row.checkStatus == 2">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['gas:fullfill:remove']">
              删除
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-printer" @click="handlePrint(scope.row)" v-hasPermi="['gas:fullfill:export']">
              打印
            </el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改充装记录
对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="充装车辆车头号" prop="getInId">
          <el-select v-model="form.getInId" placeholder="请选择车头号" @change="selectCar">
            <el-option
              v-for="car in carInfoList"
              :key="car.carHeadNum"
              :value="car.getInId"
              :label="car.carHeadNum"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车身号" prop="carBodyNum">
          <el-input v-model="form.carBodyNum" placeholder="请输入车身号" readonly />
        </el-form-item>
        <el-form-item label="所属单位" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入所属单位" readonly />
        </el-form-item>
        <el-form-item label="充气编号" prop="fullfillNum">
          <el-input v-model="form.fullfillNum" placeholder="请输入充气编号" />
        </el-form-item>
        <el-form-item label="充装气站" prop="stationId">
          <el-select v-model="form.stationId" placeholder="请选择充装气站" @change="selectStation">
            <el-option
              v-for="station in stationList"
              :key="station.stationName"
              :value="station.stationId"
              :label="station.stationName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充气量" prop="fullfillAmount">
          <el-input v-model="form.fullfillAmount" placeholder="请输入充气量">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>
        <el-form-item label="销售价格" prop="salePrice">
          <el-input v-model="form.salePrice" placeholder="请输入销售价格" readonly>
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="充装人员" prop="recordPerson">
          <el-select v-model="form.recordPerson" placeholder="请选择充装人员" @change="selectRegister">
            <el-option
              v-for="register in userList"
              :key="register.nickName"
              :value="register.nickName"
              :label="register.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充装时间" prop="recordTime">
          <el-date-picker clearable
            v-model="form.recordTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择充装时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="打印" :visible.sync="printShow" width="500px" append-to-body>
      <div ref="print">
        <h3 style="text-align: center;font-weight: bold;margin-bottom: 25px">天然气母站充装交接单</h3>
        <div style="text-align: right;margin:0 30px 5px 0">编号：  {{ printRow.fullfillNum }}</div>
        <table border="1" cellspacing="0" style="width: 100%;border-collapse: collapse;table-layout: auto">
          <tr>
            <th>充 装 日 期</th>
            <th>名 称</th>
            <th>牵引车号码</th>
            <th>挂车号码</th>
            <th>气量（m³）</th>
            <th>备注</th>
          </tr>
          <tr style="text-align: center">
            <td>{{ printRow.recordTime }}</td>
            <td>CNG压缩天然气</td>
            <td>{{ printRow.carHeadNum }}</td>
            <td>{{ printRow.carBodyNum }}</td>
            <td>{{ printRow.fullfillAmount }}</td>
            <td>{{ printRow.remark }}</td>
          </tr>
          <tr style="text-align: center">
            <th>充 装 人 员</th>
            <td>{{ printRow.recordPerson }}</td>
            <th>复核员</th>
            <td>{{ printRow.recordPerson }}</td>
            <th></th>
            <td></td>
          </tr>
        </table>
        <div style="text-align: center;font-weight: bold;margin-top: 5px">提货人签字：</div>
        <div class="no-print" slot="footer" style="text-align: right; margin-top: 15px">
          <el-button type="primary" @click="doPrint">确 定</el-button>
          <el-button @click="printCancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFullfill, getFullfill, delFullfill, addFullfill, updateFullfill, maxFillNum, todayTotal } from "@/api/gas/fullfill";
import { listStation } from "@/api/base/station";
import { listCustomer } from "@/api/base/customer";
import { getRecentCarInfoList } from "@/api/gas/get_in";
import { getUserProfile } from "@/api/system/user";
import { allocatedUserList } from "@/api/system/role";
import { getCarByCarHeadNum } from "@/api/base/car";
import format from '@/plugins/format.js'
// import print from '@/utils/print.js'

export default {
  name: "Fullfill",
  dicts: ['gas_check_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      fullfillList: [],
      // 弹出层标题
      title: "",
      printRow: {},
      // 是否显示打印弹出层
      printShow: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machineType: null,
        fullfillNum: null,
        carNumSort: null,
        fullfillAmount: null,
        salePrice: null,
        fullfillSort: null,
        recordPerson: null,
        recordTime: null,
        stationId: null,
        stationName: null,
      },
      // 表单参数
      form: {},
      customerList: [],
      customerInfoList_s: {},
      stationList: [],
      stationInfoList_s: {},
      carInfoList: [],
      carInfoList_s: {},
      userList: [],
      user: {
        nickName: "",
        phonenumber: ""
      },
      // 表单校验
      rules: {
        getInId: [
          { required: true, message: "充装车辆不能为空", trigger: "blur" }
        ],
        stationId: [
          { required: true, message: "充装气站不能为空", trigger: "blur" }
        ],
        fullfillAmount: [
          { required: true, message: "充气量不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '充气量必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        salePrice: [
          { required: true, message: "销售价格不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '销售价格必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        recordPerson: [
          { required: true, message: "充装人员不能为空", trigger: "blur" }
        ],
        recordTime: [
          { required: true, message: "充装时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询充装记录
列表 */
    getList() {
      this.loading = true;
      listFullfill(this.queryParams).then(response => {
        this.fullfillList = response.rows;
        this.total = response.total;
        this.loading = false;
        todayTotal().then(response => {
          this.fullfillList.push(response)
        })
      });
      listStation().then(response => {
        this.stationList = response.rows;
        var data_s = {};
        response.rows.forEach(function(row, index) {
          var stationInfo = {
            text: row.stationName,
            value: row.stationId
          }
          data_s[row.stationId] = row.stationName
        })
        this.stationInfoList_s = data_s
      });
      var params = {}, now = new Date();
      params.confirmTime = format(now, 'YYYY-MM-DD HH:mm:ss')
      now.setDate(now.getDate() - 5);
      params.createTime = format(now, 'YYYY-MM-DD HH:mm:ss')
      params.status = '0'
      getRecentCarInfoList(params).then(response => {
        this.carInfoList = response;
        var data_s = {};
        response.forEach(function(row, index) {
          var carInfo = {
            text: row.carHeadNum,
            value: row.getInId
          }
          data_s[row.getInId] = row
        })
        this.carInfoList_s = data_s
      });
      getUserProfile().then(response => {
        this.user = response.data
      });
      allocatedUserList({roleId: 4}).then(response => {
        this.userList = response.rows
      })
    },
    selectCar(value) {
      if (this.carInfoList_s[value]) {
        this.form.carHeadNum = this.carInfoList_s[value].carHeadNum;
        this.form.carBodyNum = this.carInfoList_s[value].carBodyNum;
        this.form.customerName = this.carInfoList_s[value].customerName;
        this.form.customerId = this.carInfoList_s[value].customerId;
        this.form.getInId = this.carInfoList_s[value].getInId;
      }
    },
    selectStation(value) {
      this.form.stationName = this.stationInfoList_s[value]
    },
    selectRegister() {

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    printCancel() {
      this.printShow = false
    },
    // 表单重置
    reset() {
      var maxFullfillNum;
      maxFillNum().then(response => {
        maxFullfillNum = parseInt(response)
        this.form = {
          fullfillId: null,
          machineType: null,
          fullfillNum: maxFullfillNum+1,
          carNumSort: null,
          fullfillAmount: null,
          salePrice: 3.25,
          fullfillSort: null,
          recordPerson: this.user.nickName,
          recordTime: new Date(),
          stationId: this.stationList[0].stationId,
          stationName: this.stationList[0].stationName,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fullfillId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fullfillId = row.fullfillId || this.ids
      getFullfill(fullfillId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fullfillId != null) {
            updateFullfill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.recordTime = format( this.form.recordTime, 'YYYY-MM-DD HH:mm:ss')
            addFullfill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleCheckPass(row) {
      var param = {
        fullfillId: row.fullfillId,
        checkStatus: "1"
      }
      this.$modal.confirm('是否确认核销"' + row.carHeadNum + '"的充装记录？').then(function() {
        return updateFullfill(param);
      }).then(() => {
        this.$modal.msgSuccess("核销成功");
        this.getList();
      }).catch(() => {});
    },
    handleCheckFail(row) {
      var param = {
        fullfillId: row.fullfillId,
        checkStatus: "2"
      }
      this.$modal.confirm('是否确认作废"' + row.carHeadNum + '"的充装记录？').then(function() {
        return updateFullfill(param);
      }).then(() => {
        this.$modal.msgSuccess("作废成功");
        this.getList();
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fullfillIds = row.fullfillId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + fullfillIds + '"的数据项？').then(function() {
        return delFullfill(fullfillIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 打印按钮操作 */
    handlePrint(row) {
      this.printShow = true
      row.recordTime = row.recordTime.replace("-", "年").replace("-", "月").replace(" ", "日 ")
      this.printRow = row

    },
    doPrint() {
      this.$print(this.$refs.print, {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gas/fullfill/export', {
        ...this.queryParams
      }, `fullfill_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
